Page({
  data: {
    userInfo: {},
    isTeacher: false,
    stat: { task: 0, fixed: 0, time: 0, group: 0 },
    examList: []
  },
  onLoad() {
    const userInfo = wx.getStorageSync('userInfo') || {};
    const user = userInfo.user || userInfo;
    this.setData({
      userInfo: user,
      isTeacher: user.identity == 1
    });
    this.getExamStat();
    this.getExamList();
  },
  getExamStat() {
    // TODO: 调用后端接口获取统计数据
    this.setData({
      stat: { task: 0, fixed: 1, time: 0, group: 0 }
    });
  },
  getExamList() {
    const user = this.data.userInfo;
    let data = {
      userId: user.id,
      identity: user.identity
    };
    // if (user.classId) data.classId = user.classId; // 这里会带上班级ID
    wx.request({
      url: 'http://localhost:9090/api/exam/listByUser',
      method: 'GET',
      data: data,
      success: res => {
        if (res.data.code == 200 || res.data.code == '200') {
          let exams = res.data.data || [];
          // 学生端处理提交状态和截止状态
          if (user.identity == 0) {
            const now = Date.now();
            exams = exams.map(item => {
              item.hasSubmitted = !!item.hasSubmitted; // 后端返回
              item.isExpired = new Date(item.examTime).getTime() < now;
              return item;
            });
          }
          // 老师端统计提交人数
          if (user.identity == 1) {
            exams.forEach((exam, idx) => {
              wx.request({
                url: 'http://localhost:9090/api/exam/submitStatus',
                method: 'GET',
                data: { examId: exam.id },
                success: r => {
                  if (r.data.code == 200 || r.data.code == '200') {
                    let submitCount = r.data.data.submitCount || 0;
                    exams[idx].submitCount = submitCount;
                    exams[idx].totalCount = r.data.data.totalCount || '-';
                    this.setData({ examList: exams });
                  }
                }
              });
            });
          }
          this.setData({
            examList: res.data.data.map(item => ({
              ...item,
              hasSubmitted: item.hasSubmitted
            }))
          });
        }
      }
    });
  },
  toExamDetail(e) {
    let item = e.currentTarget.dataset.item;
    let examId = e.currentTarget.dataset.id;
    if (!item && examId) {
      item = this.data.examList.find(exam => exam.id == examId);
    }
    if (!item) {
      wx.showToast({ title: '考试信息缺失', icon: 'none' });
      return;
    }
    // 动态设置readonly
    let readonly = 0;
    if (this.data.isTeacher) {
      readonly = 1;
    } else {
      // 学生端：已提交或已截止为只读
      readonly = (item.hasSubmitted || item.isExpired) ? 1 : 0;
    }
    wx.navigateTo({
      url: `/pages/index/examStudent/index?id=${item.id}&readonly=${readonly}`
    });
  },
  onShow() {
    if (wx.getStorageSync('refreshExamList')) {
      this.getExamList();
      wx.removeStorageSync('refreshExamList');
    }
  },
});